package com.thread.pool.application.Singleton;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

public class AtomicExample {
    private static AtomicInteger atomicInt = new AtomicInteger(0);

    public static void main(String[] args) {
        // AtomicInteger示例
        Runnable intRunnable = () -> {
            for (int i = 0; i < 10; i++) {
                int currentValue = atomicInt.getAndIncrement();
                System.out.println(Thread.currentThread().getName() + " - AtomicInteger: " + currentValue);
            }
        };
        // 创建多个线程并执行
        Thread[] threads = new Thread[5];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(intRunnable);
            threads[i].start();
        }

        atomicInt.set(0);
        // AtomicLong示例
        Runnable longRunnable = () -> {
            for (int i = 0; i < 10; i++) {
                long currentValue = atomicInt.getAndIncrement();
                System.out.println(Thread.currentThread().getName() + "longRunnable - AtomicLong: " + currentValue);
            }
        };

        Thread[] threads2 = new Thread[5];
        for (int i = 0; i < threads2.length; i++) {
            threads2[i] = new Thread(longRunnable);
            threads2[i].start();
        }
    }
}
